<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [example].
 *  example all rights reserved.
 */
namespace app\common\model;

use think\Db;
use think\Model;

/**
 * 基础模型 .
 */
class BasicModel extends Model
{
    /**
     * 数据库表名.
     *
     * @var string
     */
    protected $table;

    /**
     * 查找单条记录.
     *
     * @param string       $field 查询字段
     * @param array|string $where 查询条件
     * @param bool         $raw   是否使用RAW形式查询
     *
     * @throws Exception
     */
    protected function getItem($field = '*', $where = [], $raw = false)
    {
        try {
            $result = [];
            $dbQuery = Db::connect($this->connection)->name($this->table);

            /* raw模式查询 */
            if ($raw) {
                if (isset($where['array'])) {
                    $dbQuery->where($where['array']);
                }

                $dbQuery->whereRaw($where['str'], $where['bind']);
            } else {
                $dbQuery->where($where);
            }

            $data = $dbQuery->field($field)->find();

            if (!empty($data)) {
                $result = (array) $data;
            }

            return $result;
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 查询数量.
     *
     * @param array|string $where 查询条件
     *
     * @return float|string
     */
    protected function getCount($where = [])
    {
        return Db::connect($this->connection)->name($this->table)->where($where)->count();
    }

    /**
     * 查找多条记录.
     *
     * @param string       $field 查询字段
     * @param array|string $where 查询条件
     * @param int          $limit 限制条数
     * @param int          $page  页数
     * @param string       $order 排序
     * @param bool         $raw   是否使用RAW形式查询
     * @param array        $group 分组查询
     *
     * @throws Exception
     */
    protected function getItems(
        $field = '*',
        $where = [],
        $limit = 10,
        $page = 1,
        $order = '',
        $raw = false,
        $group = []
    ) {
        try {
            $result = [];
            $dbQuery = Db::connect($this->connection)->name($this->table);

            /* raw模式查询 */
            if ($raw) {
                if (isset($where['array'])) {
                    $dbQuery->where($where['array']);
                }

                $dbQuery->whereRaw($where['str'], $where['bind']);
            } else {
                $dbQuery->where($where);
            }

            if (!empty($group)) {
                /* 存在group */
                $dbQuery->group($group);
            }

            if ($limit > 0) {
                /* 存在limit */
                $offset = ($page - 1) * $limit;
                $dbQuery->limit($offset, $limit);
            }

            $data = $dbQuery->field($field)->order($order)->select();

            if (!empty($data)) {
                $result = (array) $data;
            }

            return $result;
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 保存数据(where不为空则更新,否则插入新数据).
     *
     * @param array        $data    保存数据
     * @param array|string $where   条件
     * @param bool         $replace 是否replace
     *
     * @throws Exception
     * @return int|string
     */
    protected function saveData($data, $where = [], $replace = false)
    {
        try {
            $dbQuery = Db::connect($this->connection)->name($this->table);

            if (empty($where)) {
                $result = $dbQuery->insert($data, $replace, true);
            } else {
                $result = $dbQuery->where($where)->update($data);
            }

            return $result;
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 批量插入/更新数据.
     *
     * @param array $datas   数据
     * @param bool  $replace 是否替换
     *
     * @return int|string
     */
    protected function insertAllDatas($datas, $replace = false)
    {
        return Db::connect($this->connection)->name($this->table)->insertAll($datas, $replace, 200);
    }

    /**
     * 插入单条记录并获取id.
     *
     * @param array $datas 数据
     *
     * @return int|string
     */
    protected function insertGetId($datas)
    {
        return Db::connect($this->connection)->name($this->table)->insertGetId($datas);
    }

    /**
     * 进行数据删除, 处理软删除.
     *
     * @return int|string
     */
    protected function deleteData($where)
    {
        $result = false;
        $dbQuery = Db::connect($this->connection)->name($this->table);

        try {
            if (method_exists($dbQuery, 'getTableFields') &&
                in_array('is_delete', $dbQuery->getTableFields())) {
                $updateData = [
                    'is_delete' => 1,
                ];

                $result = $this->saveData($updateData, $where);
            } else {
                $result = $dbQuery->where($where)->delete();
            }

            return $result;
        } catch (Exception $e) {
            throw new Exception($e->getMessage(), $e->getCode());
        }
    }
}
